package com.sample.business

import android.app.Application
import android.text.TextUtils
import com.tencent.bugly.crashreport.CrashReport
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import com.umeng.socialize.PlatformConfig
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException

object Business {

    //初始化商用SDK
    fun init(app: Application) {

        UMConfigure.init(app, Constants.UMENG_APP_ID, Constants.DEFAULT_CHANNEL, UMConfigure.DEVICE_TYPE_PHONE, "")
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)
        MobclickAgent.setCatchUncaughtExceptions(true)

        PlatformConfig.setWeixin(Constants.WECHAT_APP_ID, Constants.WECHAT_APP_SECRET)
        PlatformConfig.setQQZone(Constants.QQ_APP_ID, Constants.QQ_APP_SECRET)
        PlatformConfig.setQQFileProvider("${app.applicationInfo.packageName}.fileprovider")

        val processName = getProcessName(android.os.Process.myPid())
        val strategy = CrashReport.UserStrategy(app)
        strategy.isUploadProcess = (processName == null || processName == app.packageName)
        CrashReport.initCrashReport(app, Constants.BUGLY_APP_ID, true)

    }

    /**
     * 获取当前进程名
     */
    private fun getProcessName(pid: Int): String? {
        var reader: BufferedReader? = null
        try {
            reader = BufferedReader(FileReader("/proc/$pid/cmdline"))
            var processName = reader.readLine()
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim()
            }
            return processName
        } catch (throwable: Throwable) {
            throwable.printStackTrace()
        } finally {
            try {
                reader?.close()
            } catch (exception: IOException) {
                exception.printStackTrace()
            }
        }
        return null
    }

}